using System;
using System.Text;

namespace TlvLib.PacketParsers
{
    public abstract class PacketParserBase : IPacketParser
    {
        protected static Encoding GbkEncoding;
        protected static Encoding AsciiEncoding;
        private Action<string> _logger;

        static PacketParserBase()
        {
            GbkEncoding = Encoding.GetEncoding("GB2312");
            AsciiEncoding = Encoding.ASCII;
        }

        public Action<string> Logger
        {
            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException("Logger");
                }

                _logger = value;
            }
        }

        public abstract bool CanParse(RawPacket packet);
        public abstract object Parse(RawPacket packet);

        protected int CountNonZero(byte[] buffer)
        {
            var i = 0;
            for (i = 0; i < buffer.Length; i++)
            {
                if (buffer[i] == 0)
                {
                    break;
                }
            }

            return i;
        }

        protected void Log(string message)
        {
            if (_logger != null)
            {
                _logger(message);
            }
        }

        protected DateTime ReadTime(MiscUtil.IO.EndianBinaryReader reader)
        {
            var year = reader.ReadInt16();
            var month = reader.ReadInt16();
            var day = reader.ReadInt16();
            var hour = reader.ReadInt16();
            var minute = reader.ReadInt16();
            var second = reader.ReadInt16();
            var millisecond = reader.ReadInt16();

            return new DateTime(year, month, day, hour, minute, second, millisecond);
        }
    }
}